package org.ilc.util;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;


/**
 * 固定密码　解密
 * @author xm
 *
 */
public class CipherUtil {

	private static String  IV="53641051";
	private static String  KEY="PZEpH530";

	public static String encode(String data,String key) throws Exception {
		
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(IV.getBytes("utf-8"));

		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

		byte[] retByte = cipher.doFinal(data.getBytes("UTF-8"));
//		return new BASE64Encoder().encode(retByte);
        byte [] encodeByte = Base64.encodeBase64 (retByte);
        return new String (encodeByte);

	}
	
	public static String encode(String data) throws Exception {
		if(null==data ||"".equals(data.trim())){
			return data;
		}
		return encode(data,KEY);

	}
	public static String decrypt(String message,String key) throws Exception {
//		BASE64Decoder decoder = new BASE64Decoder();
//		byte[] bytesrc = decoder.decodeBuffer(message);
        byte [] bytesrc = Base64.decodeBase64 (message.getBytes ());
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(IV.getBytes("UTF-8"));

		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte);

	}

	public static String decrypt(String message) throws Exception {
		if(null==message ||"".equals(message.trim())){
			return message;
		}
		return decrypt(message,KEY);

	}

}
